package com.xudow.app.ui;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.activeshare.edu.ucenter.common.messages.study.WrongMessage;
import com.activeshare.edu.ucenter.models.base.WorStudentWrongTopic;
import com.activeshare.edu.ucenter.models.base.WorWrongTopicImage;
import com.xudow.app.Config;
import com.xudow.app.R;
import com.xudow.app.ui.task.ClazzMistakeCreateTask;
import com.xudow.app.ui.task.ClazzMistakeImageDeleteTask;
import com.xudow.app.ui.task.ClazzMistakeShowTask;
import com.xudow.app.ui.task.ClazzMistakeTask;
import com.xudow.app.util.AlbumUtil;
import com.xudow.app.util.ImageUtils;
import com.xudow.app.util.Maps;
import com.xudow.app.util.StringUtils;

import org.apmem.tools.layouts.FlowLayout;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 错题详情Activity
 *
 * @author lukecheng
 */
public class ClazzMistakeDetailActivity extends BaseActivity implements View.OnClickListener {

    private static final int ALBUM_OK_KITKAT = 200;
    private static final int ALBUM_OK = 201;
    private static final int CAMERA_OK = 202;

    private static final int MISTAKE_CORRECT = 2;  //正确图片类型
    private static final int MISTAKE_ERROR = 1;  //错误图片类型

    /**
     * 图片大小
     */
    private static final int IMAGE_WIDTH = 150;
    private static final int IMAGE_HEIGHT = 150;

    private static final int REQUEST_SUBJECTS = 1024;

    private String studentId;
    private String subjectName;
    private String subjectId;
    private String method;
    private String mistakeId; //错题id

    private EditText subjectEditText, titleEditText, commentEditText;
    private FlowLayout correctImageLayout, errorImageLayout;

    private List<ImageView> errorImageViews;
    private List<ImageView> correctImageViews;

    private ImageTag currentTag;

    private File tempFile;

    private ClazzMistakeCreateTask clazzMistakeCreateTask;
    private ClazzMistakeShowTask clazzMistakeShowTask;
    private ClazzMistakeImageDeleteTask clazzMistakeImageDeleteTask;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_clazz_mistake_detail);

        subjectEditText = (EditText) findViewById(R.id.subject);
        titleEditText = (EditText) findViewById(R.id.title);
        commentEditText = (EditText) findViewById(R.id.comment);

        method = getIntent().getStringExtra("method");
        if ("create".equals(method)) {
            //新建错题
            ((TextView) findViewById(R.id.page_title)).setText(getString(R.string.title_activity_clazz_mistake_create));

            studentId = getIntent().getStringExtra("studentId");
            subjectName = getIntent().getStringExtra("subjectName");
        } else {
            //查看错题
            studentId = getIntent().getStringExtra("studentId");
            mistakeId = getIntent().getStringExtra("wrongid");
            subjectName = getIntent().getStringExtra("subjectName");
        }

        correctImageLayout = (FlowLayout) findViewById(R.id.correct_images);
        errorImageLayout = (FlowLayout) findViewById(R.id.error_images);

        subjectEditText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(ClazzMistakeDetailActivity.this, SubjectsActivity.class);
                intent.putExtra("studentId", studentId);

                startActivityForResult(intent, REQUEST_SUBJECTS);
            }
        });

        errorImageViews = new ArrayList<ImageView>();
        correctImageViews = new ArrayList<ImageView>();

        errorImageViews.add(createImageView(R.mipmap.plus, true));
        correctImageViews.add(createImageView(R.mipmap.plus, false));

        initImages();

        if ("show".equals(method)) {
            showLodingDialog(getString(R.string.loading));

            HashMap<String, String> params = Maps.newHashMap();
            params.put("wrongid", mistakeId);

            clazzMistakeShowTask = new ClazzMistakeShowTask(this, clazzMistakeShowHandler);
            addTask(clazzMistakeShowTask);
            clazzMistakeShowTask.execute(params);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case REQUEST_SUBJECTS:
                if (RESULT_OK == resultCode) {
                    Bundle b = data.getExtras();
                    subjectName = b.getString("subjectName");
                    subjectId = b.getString("subjectId");
                    subjectEditText.setText(subjectName);
                }
                break;
            case ALBUM_OK:
                if (data != null) {
                    onSelectImageSuccess(data.getData());
                }
                break;
            case ALBUM_OK_KITKAT:
                if (data != null) {
                    Uri uri = Uri.parse(AlbumUtil.getPath(this, data.getData()));
                    onSelectImageSuccess(uri);
                }
                break;
            case CAMERA_OK:
                if (RESULT_OK == resultCode) {
                    onSelectImageCameraSuccess();
                }
                break;
            default:
                break;
        }
    }

    /**
     * 成功从相机获取图片
     */
    private void onSelectImageCameraSuccess() {
        if (currentTag.isError) {
            errorImageViews.add(0, createImageView(Uri.fromFile(tempFile), true));
        } else {
            correctImageViews.add(0, createImageView(Uri.fromFile(tempFile), false));
        }

        initImages();
    }

    /**
     * 成功从文件夹获取图片
     *
     * @param uri
     */
    private void onSelectImageSuccess(Uri uri) {
        if (null == uri) {
            return;
        }

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
            uri = Uri.parse("file:///" + uri.toString());
        }

        if (currentTag.isError) {
            errorImageViews.add(0, createImageView(uri, true));
        } else {
            correctImageViews.add(0, createImageView(uri, false));
        }

        initImages();
    }

    public void onBackBtnClick(View view) {
        if (clazzMistakeCreateTask != null && !clazzMistakeCreateTask.isCancelled()) {
            clazzMistakeCreateTask.cancel(true);
            clazzMistakeCreateTask = null;
        }

        if (clazzMistakeShowTask != null && !clazzMistakeShowTask.isCancelled()) {
            clazzMistakeShowTask.cancel(true);
            clazzMistakeShowTask = null;
        }

        if (clazzMistakeImageDeleteTask != null && !clazzMistakeImageDeleteTask.isCancelled()) {
            clazzMistakeImageDeleteTask.cancel(true);
            clazzMistakeImageDeleteTask = null;
        }

        finish();
    }

    /**
     * 确定按钮点击事件
     *
     * @param view
     */
    public void onCreateClick(View view) {
        String title = titleEditText.getText().toString().trim();
        if (StringUtils.isEmpty(title)) {
            titleEditText.setError(getString(R.string.title_required));
            return;
        }

        String subject = subjectEditText.getText().toString();
        if (StringUtils.isEmpty(subject)) {
            subjectEditText.setError(getString(R.string.subject_required));
            return;
        }

        String comment = commentEditText.getText().toString().trim();

        HashMap<String, Object> params = Maps.newHashMap();
        params.put("studentid", studentId);
        params.put("subjectid", subjectId);
        params.put("title", title);
        params.put("remark", comment);

        if ("show".equals(method)) {
            params.put("wrongid", mistakeId);
        }

        List<String> correctImageUris = new ArrayList<String>();
        for (int i = 0; i < correctImageViews.size() - 1; i++) {
            ImageTag tag = (ImageTag) correctImageViews.get(i).getTag();

            if (tag.isNewImage) {
                Uri uri = Uri.parse(tag.info);
                correctImageUris.add(AlbumUtil.getPath(this, uri));
            }
        }

        List<String> errorImageUris = new ArrayList<String>();
        for (int i = 0; i < errorImageViews.size() - 1; i++) {
            ImageTag tag = (ImageTag) errorImageViews.get(i).getTag();

            if (tag.isNewImage) {
                Uri uri = Uri.parse(tag.info);
                errorImageUris.add(AlbumUtil.getPath(this, uri));
            }
        }

        params.put("correct", correctImageUris);
        params.put("error", errorImageUris);

        showLodingDialog(getString(R.string.processing));

        clazzMistakeCreateTask = new ClazzMistakeCreateTask(this, mistakeCreateHandler);
        addTask(clazzMistakeCreateTask);
        clazzMistakeCreateTask.execute(params);
    }

    /**
     * 出题创建Handler
     */
    private Handler mistakeCreateHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (ClazzMistakeTask.SUCCESS == msg.what) {
                String message = getString(R.string.process_success);
                Toast.makeText(ClazzMistakeDetailActivity.this, message, Toast.LENGTH_SHORT).show();

                finish();
            } else {
                String message = getString(R.string.process_fail);
                Toast.makeText(ClazzMistakeDetailActivity.this, message, Toast.LENGTH_SHORT).show();
            }
        }
    };

    /**
     * 从res创建ImageView
     *
     * @param resId
     * @param isError 是否错题图片
     * @return
     */
    private ImageView createImageView(int resId, boolean isError) {
        ImageView view = new ImageView(this);

        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(IMAGE_WIDTH, IMAGE_HEIGHT);
        params.setMargins(0, 0, 10, 0);
        view.setMinimumHeight(IMAGE_HEIGHT);
        view.setMinimumWidth(IMAGE_WIDTH);
        view.setMaxHeight(IMAGE_HEIGHT);
        view.setMaxWidth(IMAGE_WIDTH);

        view.setPadding(0, 0, 10, 0);

        view.setLayoutParams(params);
        view.setImageResource(resId);

        ImageTag tag = new ImageTag(isError, ImageTag.TYPE_RES_ID, "" + resId);
        tag.isPlusBtn = true;
        view.setTag(tag);

        view.setOnClickListener(this);

        return view;
    }

    /**
     * 从本地Uri创建ImageView
     *
     * @param uri
     * @return
     */
    private ImageView createImageView(Uri uri, boolean isError) {
        ImageView view = new ImageView(this);

        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(IMAGE_WIDTH, IMAGE_HEIGHT);
        params.setMargins(0, 0, 10, 0);
        view.setMinimumHeight(IMAGE_HEIGHT);
        view.setMinimumWidth(IMAGE_WIDTH);
        view.setMaxHeight(IMAGE_HEIGHT);
        view.setMaxWidth(IMAGE_WIDTH);

        view.setPadding(0, 0, 10, 0);

        view.setLayoutParams(params);
        view.setImageBitmap(AlbumUtil.getBitmapFromUri(this, uri));

        ImageTag tag = new ImageTag(isError, ImageTag.TYPE_URI, uri.toString());
        tag.isNewImage = true;
        view.setTag(tag);

        view.setOnClickListener(this);

        return view;
    }

    /**
     * 从网络创建ImageView
     *
     * @param url
     * @param isError
     * @return
     */
    private ImageView createImageView(String url, String orignUrl, Long imageId, boolean isError) {
        ImageView view = new ImageView(this);

        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(IMAGE_WIDTH, IMAGE_HEIGHT);

        view.setMinimumHeight(IMAGE_HEIGHT);
        view.setMinimumWidth(IMAGE_WIDTH);
        view.setMaxHeight(IMAGE_HEIGHT);
        view.setMaxWidth(IMAGE_WIDTH);

        view.setPadding(0, 0, 10, 0);

        params.setMargins(0, 0, 10, 0);
        view.setLayoutParams(params);

        ImageTag tag = new ImageTag(isError, ImageTag.TYPE_NETWORK, url);
        tag.origin = orignUrl;
        tag.imageId = imageId;
        view.setTag(tag);

        view.setOnClickListener(this);

        String absUrl = String.format(Config.IMAGE_LOAD_URL_PARAMS, url);
        ImageUtils.loadImage(this, view, absUrl, R.mipmap.course_def_img);

        return view;
    }

    private void initImages() {
        errorImageLayout.removeAllViews();
        for (int i = 0; i < errorImageViews.size(); i++) {
            errorImageLayout.addView(errorImageViews.get(i));
        }

        correctImageLayout.removeAllViews();
        for (int i = 0; i < correctImageViews.size(); i++) {
            correctImageLayout.addView(correctImageViews.get(i));
        }
    }

    @Override
    public void onClick(View v) {
        final ImageView view = (ImageView) v;
        currentTag = (ImageTag) view.getTag();

        if (currentTag.isPlusBtn) {
            //添加图片按钮
            final String[] options = {
                    getString(R.string.from_camera),
                    getString(R.string.from_album)
            };

            AlertDialog.Builder dlg = new AlertDialog.Builder(this);
            dlg.setItems(options, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if (0 == which) {
                        takeImageFromCamera();
                    } else {
                        takeImageFromAlbum();
                    }
                }
            });
            dlg.create().show();
        } else {
            final String[] options = {
                    getString(R.string.image_view),
                    getString(R.string.image_delete)
            };

            AlertDialog.Builder dlg = new AlertDialog.Builder(this);
            dlg.setItems(options, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if (0 == which) {
                        //查看图片
                        showImage(view);
                    } else {
                        //删除图片
                        deleteImage(view);
                    }
                }
            });
            dlg.create().show();
        }
    }

    /**
     * 查看图片
     *
     * @param view
     */
    private void showImage(ImageView view) {
        ImageTag tag = (ImageTag) view.getTag();

        if (tag.type == ImageTag.TYPE_URI) {
            Uri uri = Uri.parse(tag.info);

            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(uri, "image/*");
            startActivity(intent);
        } else if (tag.type == ImageTag.TYPE_NETWORK) {
            String url = String.format(Config.IMAGE_LOAD_URL_PARAMS, tag.origin);

            ImageViewPopup imageViewPopup = new ImageViewPopup(this, url);
            imageViewPopup.showAtLocation(findViewById(R.id.root), Gravity.CENTER, 0, 0);
        }
    }

    /**
     * 删除图片
     *
     * @param view
     */
    private void deleteImage(ImageView view) {
        ImageTag tag = (ImageTag) view.getTag();

        if (tag.type == ImageTag.TYPE_NETWORK) {
            showLodingDialog(getString(R.string.processing));

            HashMap<String, String> params = Maps.newHashMap();
            params.put("imageid", "" + tag.imageId);

            clazzMistakeImageDeleteTask = new ClazzMistakeImageDeleteTask(this, clazzMistakeImageDeleteHandler);
            addTask(clazzMistakeImageDeleteTask);
            clazzMistakeImageDeleteTask.execute(params);
        } else {
            for (int i = 0; i < errorImageViews.size(); i++) {
                if (errorImageViews.get(i).equals(view)) {
                    errorImageViews.remove(i);
                    break;
                }
            }

            for (int i = 0; i < correctImageViews.size(); i++) {
                if (correctImageViews.get(i).equals(view)) {
                    correctImageViews.remove(i);
                    break;
                }
            }

            initImages();
        }
    }

    public void deleteNetworkImage(Long imageId) {
        for (int i = 0; i < errorImageViews.size(); i++) {
            ImageTag tag = (ImageTag) errorImageViews.get(i).getTag();
            if (tag.imageId != null && tag.imageId == imageId) {
                errorImageViews.remove(i);
                break;
            }
        }

        for (int i = 0; i < correctImageViews.size(); i++) {
            ImageTag tag = (ImageTag) correctImageViews.get(i).getTag();
            if (tag.imageId != null && tag.imageId == imageId) {
                correctImageViews.remove(i);
                break;
            }
        }

        initImages();
    }

    /**
     * 从相册选择图片
     */
    private void takeImageFromAlbum() {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
            AlbumUtil.fromAlbum(this, ALBUM_OK_KITKAT);
        } else {
            AlbumUtil.fromAlbum(this, ALBUM_OK);
        }
    }

    /**
     * 拍照获取图片
     */
    private void takeImageFromCamera() {
        if (!new File(Config.SDCARD_ROOT_DIR).exists()) {
            new File(Config.SDCARD_ROOT_DIR).mkdirs();
        }

        String filename = System.currentTimeMillis() + ".jpg";
        tempFile = new File(Config.SDCARD_ROOT_DIR + "/" + filename);

        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra("output", Uri.fromFile(tempFile));
        startActivityForResult(intent, CAMERA_OK);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (KeyEvent.KEYCODE_BACK == keyCode) {
            if (clazzMistakeCreateTask != null && !clazzMistakeCreateTask.isCancelled()) {
                clazzMistakeCreateTask.cancel(true);
                clazzMistakeCreateTask = null;
            }

            if (clazzMistakeShowTask != null && !clazzMistakeShowTask.isCancelled()) {
                clazzMistakeShowTask.cancel(true);
                clazzMistakeShowTask = null;
            }

            if (clazzMistakeImageDeleteTask != null && !clazzMistakeImageDeleteTask.isCancelled()) {
                clazzMistakeImageDeleteTask.cancel(true);
                clazzMistakeImageDeleteTask = null;
            }
        }

        return super.onKeyDown(keyCode, event);
    }

    /**
     * 获取错题详情Handler
     */
    private Handler clazzMistakeShowHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            hideLoadingDialog();

            if (ClazzMistakeShowTask.SUCCESS == msg.what) {
                WrongMessage wrongMessage = (WrongMessage) msg.getData().getSerializable("mistake");

                onShowSuccess(wrongMessage);
            } else {
                String message = getString(R.string.loading_fail);
                Toast.makeText(ClazzMistakeDetailActivity.this, message, Toast.LENGTH_SHORT).show();
            }
        }
    };

    /**
     * 获取错题详情Handler
     *
     * @param wrongMessage
     */
    private void onShowSuccess(WrongMessage wrongMessage) {
        List<WorWrongTopicImage> wrongTopicImages = wrongMessage.getImages();
        WorStudentWrongTopic wrongTopic = wrongMessage.getWrongTopic();

        titleEditText.setText(wrongTopic.getTitle());
        commentEditText.setText(wrongTopic.getRemark());
        subjectEditText.setText(subjectName);
        subjectId = "" + wrongTopic.getSubjectId();

        for (WorWrongTopicImage img : wrongTopicImages) {
            if (img.getType() == MISTAKE_CORRECT) {
                correctImageViews.add(0,
                        createImageView(img.getThumbnailPath(), img.getUrl(), img.getId(), false));
            } else {
                errorImageViews.add(0,
                        createImageView(img.getThumbnailPath(), img.getUrl(), img.getId(), true));
            }
        }

        initImages();
    }

    /**
     * 删除图片Handler
     */
    private Handler clazzMistakeImageDeleteHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            hideLoadingDialog();

            if (ClazzMistakeImageDeleteTask.SUCCESS == msg.what) {
                String imageId = msg.getData().getString("imageId");
                deleteNetworkImage(Long.parseLong(imageId));
            } else {
                String message = getString(R.string.process_fail);
                Toast.makeText(ClazzMistakeDetailActivity.this, message, Toast.LENGTH_SHORT).show();
            }
        }
    };

    /**
     * 图片信息
     */
    class ImageTag {
        public final static int TYPE_RES_ID = 0; //res文件
        public final static int TYPE_URI = 1; //本地Uri文件
        public final static int TYPE_NETWORK = 2; //网络图片

        public boolean isError;
        public int type;
        public String info; //resId, uri或者缩略图
        public String origin; //如果是网络图片，info保存的是缩略图，origin保存完整图片地址
        public Long imageId; //如果是网络图片,需要设置该id
        public boolean isPlusBtn; //是否是添加按钮图片
        public boolean isNewImage; //是不是新增加的

        public ImageTag(boolean isError, int type, String info) {
            this.isError = isError;
            this.type = type;
            this.info = info;
        }
    }
}
